import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // 启动要显示的界面
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _counter = 100;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("图标组件示例"),
      ),
      body: JKCounterWidget(
        counter: _counter,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              JKShowData01(),
              JKShowData02()
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          setState(() {
            _counter++;
          });
        },
      ),
    );
  }
}

class JKShowData01 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int counter = JKCounterWidget.of(context).counter;

    return Card(
      color: Colors.brown,
      child: Text('当前计数：$counter', style: TextStyle(fontSize: 30, color: Colors.white),),
    );
  }
}

class JKShowData02 extends StatefulWidget {
  @override
  _JKShowData02State createState() => _JKShowData02State();
}

class _JKShowData02State extends State<JKShowData02> {

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();

    print('执行了');
  }

  @override
  Widget build(BuildContext context) {
    int counter = JKCounterWidget.of(context).counter;

    return Card(
      color: Colors.green,
      child: Text('当前计数：$counter', style: TextStyle(fontSize: 30, color: Colors.white),),
    );
  }
}

class JKCounterWidget extends InheritedWidget {
  /* 1.共享的数据 */
  final int counter;

  /* 2.自定义的构造方法 */
  JKCounterWidget({this.counter, Widget child}): super(child: child);

  /* 3.获取组件最近的当前的InheritedWidget */
  static JKCounterWidget of(BuildContext context) {
    /* 沿着Element树去找到最近的JKJKCounterElement, 从Element里面取出Widget对象 */
    return context.dependOnInheritedWidgetOfExactType();
  }

  /* 4.决定要不要回调State中didChangeDependencies() */
  /* 如果返回True, 执行依赖当期的InheritedWidget的State中的didChangeDependencies()，反之不会执行didChangeDependencies() */
  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }
}